﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EC18_ESHOP.Models;
using WebMatrix.WebData;
using System.IO;
using System.Web.Hosting;
using System.Text;
using System.Data.Entity.Validation;
using ImageResizer;

namespace EC18_ESHOP.Areas.Admin.Controllers
{
    [AdminAuthorize]
    public class AdminHomeController : Controller
    {
        EShopEntities db = new EShopEntities();
        //
        // GET: /Admin/AdminHome/

        public ActionResult Index()
        {
            return RedirectToAction("MyProfile", "AdminHome");
        }


        public ActionResult MyProfile(int id = 0)
        {
            ViewBag.Notify = id;
            UserProfile user = db.UserProfile.Find(WebSecurity.CurrentUserId);
            if (Request.Cookies["avatar"] == null)
            {
                var avatar = user.Avatar;
                Response.AppendCookie(new HttpCookie("avatar", avatar));
            }
            return View(user);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateProfile(HttpPostedFileBase inputavatar, FormCollection updateform)
        {
            UserProfile user = db.UserProfile.Find(WebSecurity.CurrentUserId);
            DateTime day = DateTime.ParseExact(updateform["DOB"], "dd-MM-yyyy", null);
            user.DOB = new Nullable<DateTime>(day);
            user.Email = updateform["Email"];
            user.Numberphone = updateform["Numberphone"];
            user.Sex = Convert.ToBoolean(updateform["Sex"]);
            if (inputavatar != null && inputavatar.ContentLength > 0)
            {
                var fileName = System.IO.Path.GetFileName(inputavatar.FileName);
                var path = System.IO.Path.Combine(Server.MapPath("~/Content/assets/avatars"), fileName);
                inputavatar.SaveAs(path);

                user.Avatar = "/Content/assets/avatars/" + fileName;
                HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["avatar"];
                cookie.Value = user.Avatar;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }

            try
            {
                db.SaveChanges();
            }
            catch
            {
                return RedirectToAction("MyProfile", new { id = 3 });
            }

            if (updateform["currentpass"] != "" && updateform["newpass"] != "")
            {
                if (WebSecurity.ChangePassword(user.UserName, updateform["currentpass"], updateform["newpass"]))
                {
                    return RedirectToAction("MyProfile", new { id = 1 });
                }
                else
                {
                    return RedirectToAction("MyProfile", new { id = 2 });
                }
            }

            return RedirectToAction("MyProfile", new { id = 1 });
        }


        //add new product
        //GET: /Admin/AdminHome/addNewProduct
        public ActionResult addNewProduct(int status = 0)
        {
            ViewBag.Status = status;
            ViewBag.CategoryId = new SelectList(db.CATEGORY, "Category_Id", "CategoryName");
            ViewBag.ManufacturerId = new SelectList(db.MANUFACTURER, "ManufacturerId", "ManufacturerName");
            ViewBag.arrCategory = db.CATEGORY.Where(p => p.CategoryParent != null).ToList();
            return View();
        }

        //add new product
        //POST: /Admin/AdminHome/addNewProduct
        [HttpPost]
        public ActionResult addNewProduct(PRODUCT product)
        {
            if (ModelState.IsValid)
            {
                if (db.PRODUCT.Where(p => p.ProductId == product.ProductId).ToList().Count == 0)
                {
                    product.QuantityInReserve = 0;
                    product.QuantiTyOfLike = 0;
                    product.QuantityOfSale = 0;
                    product.QuantityOfShare = 0;
                    product.QuantityOfView = 0;
                    product.Status = true;
                    product.TotalRating = 0;
                    product.ModifyBy = WebSecurity.GetUserId(User.Identity.Name);
                    db.PRODUCT.Add(product);
                    db.SaveChanges();

                    //images
                    funtionFileUpload(HttpContext, product.ProductId);
                    return RedirectToAction("addNewProduct", "AdminHome", new { status = 1 });
                }
                else
                    return RedirectToAction("addNewProduct", "AdminHome", new { status = 2 });
            }
            else
                return RedirectToAction("addNewProduct", "AdminHome", new { status = 3 });
        }

        //update product
        //POST: /Admin/AdminHome/updateProduct
        public ActionResult updateProduct(int productId, int status = 0)
        {

            PRODUCT product = db.PRODUCT.Find(productId);
            if (product != null)
            {
                ViewBag.product = product;
                ViewBag.arrCategory = db.CATEGORY.Where(p => p.CategoryParent != null).ToList();
                ViewBag.arrManufactory = db.MANUFACTURER.ToList();
                ViewBag.arrProperty = db.PROPERTY.Where(p => p.CategoryBelongTo == product.CATEGORY.CategoryParent).ToList();
                //lấy hết ảnh sản phẩm
                ViewBag.arrImg = getListUrlImages(product.ProductId);
                ViewBag.status = status;
            }
            return View();
        }

        //update product
        //POST: /Admin/AdminHome/updateProductPost
        public ActionResult updateProductPost(PRODUCT product)
        {
            if (ModelState.IsValid)
            {
                PRODUCT item = db.PRODUCT.Find(product.Product_ID);
                if (item != null)
                {
                    item.ProductId = product.ProductId;
                    item.ProductName = product.ProductName;
                    item.ProductPrice = product.ProductPrice;
                    item.Description = product.Description;
                    item.ManufacturerId = product.ManufacturerId;
                    item.MANUFACTURER = db.MANUFACTURER.Find(product.ManufacturerId);
                    item.CategoryId = product.CategoryId;
                    item.CATEGORY = db.CATEGORY.Find(product.CategoryId);
                    item.ModifyBy = WebSecurity.GetUserId(User.Identity.Name);
                    db.SaveChanges();
                    //images
                    funtionFileUpload(HttpContext, product.ProductId);

                    return RedirectToAction("updateProduct", "AdminHome", new { productId = item.Product_ID, status = 1 });
                }
                else
                    return RedirectToAction("updateProduct", "AdminHome", new { productId = item.Product_ID, status = 2 });
            }
            else
                return RedirectToAction("updateProduct", "AdminHome", new { productId = product.Product_ID, status = 3 });
        }

        //get all images of a product using productId
        public List<string> getListUrlImages(string productId)
        {
            List<string> _Url = new List<string>();
            string _root = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
            DirectoryInfo _direc = new DirectoryInfo(HostingEnvironment.MapPath(@"~\Images\Product\" + productId));
            var file = _direc.GetFiles("*.jpg").ToList();
            for (int i = 0; i < file.Count; i++)
            {
                string temp = file[i].ToString();
                if (temp.Substring(temp.Length - 5, 1) != "b")
                    _Url.Add(_root + "/Images/Product/" + productId + "/" + file[i].ToString());
            }
            return _Url;
        }

        //retrieve list product
        //GET: /Admin/AdminHome/retrieveAllProduct
        public ActionResult retrieveAllProduct(int val = 0)
        {
            List<PRODUCT> arrProduct = new List<PRODUCT>();
            try
            {
                switch (val)
                {
                    case 1:
                        arrProduct = db.PRODUCT.Where(p => p.CATEGORY.CategoryParent == 28).ToList();
                        ViewBag.selected = "Đồ gia dụng";
                        break;
                    case 2:
                        arrProduct = db.PRODUCT.Where(p => p.CATEGORY.CategoryParent == 6).ToList();
                        ViewBag.selected = "Đồ điện tử";
                        break;
                    case 3:
                        arrProduct = db.PRODUCT.Where(p => p.CATEGORY.CategoryParent == 1).ToList();
                        ViewBag.selected = "Đồ điện lạnh";
                        break;
                    default:
                        arrProduct = db.PRODUCT.Where(p => p.CATEGORY.CategoryParent == 6).ToList();
                        ViewBag.selected = "Đồ điện tử";
                        break;
                }
                ViewBag.arrProduct = arrProduct;
            }
            catch (Exception ex) { }
            return View();
        }

        //retrieve product by Id
        //POST: /Admin/AdminHome/
        public JsonResult retrieveProductById(string productId)
        {
            List<PRODUCT> arrProduct = db.PRODUCT.Where(p => p.ProductId == productId).ToList();
            if (arrProduct.Count == 1)
            {
                ViewBag.arrProduct = arrProduct;
                return Json(new { data = true });
            }
            else
                return Json(new { data = false });
        }

        //disable product (delete)
        //POST: /Admin/AdminHome/disableProduct
        public JsonResult disableProduct(int productId)
        {
            PRODUCT product = db.PRODUCT.Find(productId);
            if (product != null)
            {
                product.Status = false;
                db.SaveChanges();
                return Json(new { data = true });
            }
            else return Json(new { data = false });
        }

        //enable product
        //POST: /Admin/AdminHome/enableProduct
        public JsonResult enableProduct(int productId)
        {
            PRODUCT product = db.PRODUCT.Find(productId);
            if (product != null)
            {
                product.Status = true;
                db.SaveChanges();
                return Json(new { data = true });
            }
            else return Json(new { data = false });
        }

        //add new category
        //POST: /Admin/AdminHome/addCategory
        public JsonResult addCategory(string categoryName, int categoryParent)
        {
            try
            {
                if (categoryName != "")
                {
                    CATEGORY category = new CATEGORY();
                    category.CategoryName = categoryName;
                    if (categoryParent == 0)
                        category.CategoryParent = null;
                    else
                        category.CategoryParent = categoryParent;
                    db.CATEGORY.Add(category);
                    db.SaveChanges();
                }
            }
            catch (Exception ex) { }

            string result = "<select id='drlCategory'>";
            List<CATEGORY> arr = db.CATEGORY.ToList();
            foreach (CATEGORY item in arr)
            {
                result += "<option id='" + item.Category_Id + "'>" + item.CategoryName + "</option>";
            }
            result += "</select>";
            return Json(new { data = result });
        }

        //add new manufacturer
        //POST: /Admin/AdminHome/addManufacturer
        public JsonResult addManufacturer(string manufacturerName)
        {
            try
            {
                List<MANUFACTURER> temp = db.MANUFACTURER.Where(p => p.ManufacturerName == manufacturerName).ToList();
                if (temp.Count == 0)
                {
                    MANUFACTURER manu = new MANUFACTURER();
                    manu.ManufacturerName = manufacturerName;
                    db.MANUFACTURER.Add(manu);
                    db.SaveChanges();
                }
            }
            catch (Exception ex) { }
            string result = "<select id='drlManufacturer'>";
            List<MANUFACTURER> arr = db.MANUFACTURER.ToList();
            foreach (MANUFACTURER item in arr)
            {
                result += "<option id='" + item.ManufacturerId + "'>" + item.ManufacturerName + "</option>";
            }
            result += "</select>";
            return Json(new { data = result });
        }


        //get all product property of a product in html style
        public string getHtmlOfProductProperty(int productId)
        {
            string result = "";
            List<PRODUCT_PROPERTIES> arrPP = db.PRODUCT_PROPERTIES.Where(p => p.ProductId == productId).ToList();
            result += ("<table class='table'><tr><th>Thông số</th><th>Giá trị</th><th>Chỉnh sửa</th></tr>");
            foreach (PRODUCT_PROPERTIES item in arrPP)
            {
                result += ("<tr><td class='PropertyName'>" + item.PROPERTY.PropertyName + "</td><td class='PropertyValue'>" + HttpUtility.HtmlDecode(item.Value) + "</td><td><div class='hidden-phone visible-desktop action-buttons'>");
                result += ("<a class='green' href='#' onclick='showModalProperty('" + item.ProductId + "','" + item.PROPERTY.PropertyName + "','" + item.Value + "')'><i class='icon-pencil bigger-130'></i>");
                result += ("</a> <a class='red'><i class='icon-trash bigger-130'></i></a></div></td></tr>");
            }
            return result;
        }

        //update product property
        //POST: /Admin/AdminHome/updateProductProperty
        public JsonResult updateProductProperty(string propertyValue, int propertyId, int productId)
        {
            List<PRODUCT_PROPERTIES> arrPP = db.PRODUCT_PROPERTIES.Where(p => p.PropertyId == propertyId)
                                    .Where(p => p.ProductId == productId).ToList();
            if (arrPP.Count == 1)
            {
                PRODUCT_PROPERTIES pp = arrPP[0];
                pp.Value = propertyValue;
                db.SaveChanges();
            }
            return Json(new { data = getHtmlOfProductProperty(productId) });
        }

        //add new product property
        //POST: /Admin/AdminHome/addNewProductProperty
        public JsonResult addNewProductProperty(int productId, int propertyId, string value, bool isImportant)
        {
            if (db.PRODUCT_PROPERTIES.Where(p => p.PropertyId == propertyId)
                                    .Where(p => p.ProductId == productId).ToList().Count == 0)
            {
                PRODUCT_PROPERTIES pp = new PRODUCT_PROPERTIES();
                pp.ProductId = productId;
                pp.PropertyId = propertyId;
                pp.Value = value;
                pp.IsImportant = isImportant;
                db.PRODUCT_PROPERTIES.Add(pp);
                db.SaveChanges();
            }
            return Json(new { data = getHtmlOfProductProperty(productId) });
        }


        //delete product property
        //POST: /Admin/AdminHome/deleteProductProperty
        public JsonResult deleteProductProperty(int productId, int propertyId)
        {
            if (db.PRODUCT_PROPERTIES.Where(p => p.PropertyId == propertyId)
                                    .Where(p => p.ProductId == productId).ToList().Count == 1)
            {
                PRODUCT_PROPERTIES pp = db.PRODUCT_PROPERTIES.Where(p => p.PropertyId == propertyId)
                                    .Where(p => p.ProductId == productId).ToList()[0];
                db.PRODUCT_PROPERTIES.Remove(pp);
                db.SaveChanges();
            }
            return Json(new { data = getHtmlOfProductProperty(productId) });
        }

        //delete image of product
        //POST: Admin/AdminHome/deleteImage
        public JsonResult deleteImage(string url, string productId)
        {
            //if ((System.IO.File.Exists(url)))
            {
                System.IO.File.Delete(url);
            }

            List<string> arrImg = getListUrlImages(productId);
            string result = "<h5 class='header green clearfix'>Hình ảnh sản phẩm</h5><table class='table'>";
            foreach (string item in arrImg)
            {
                result += "<tr><td style='width: 300px'><img src='" + item + "' /></td><td style='width: 600px'>";
                result += "<div class='hidden-phone visible-desktop action-buttons'>";
                result += "<a class='red' onclick ='deleteImage('" + item + "', '" + productId + "')'>";
                result += "<i class='icon-trash bigger-130'></i></a></div></td></tr>";
            }
            result += "</table>";
            return Json(new { data = result });
        }


        //file upload for images of product
        public void funtionFileUpload(HttpContextBase context, string productId)
        {
            Dictionary<string, string> versions = new Dictionary<string, string>();
            //Define the versions to generate
            versions.Add("-s", "maxwidth=420&maxheight=420&format=jpg"); //Fit inside 400x400 area, jpeg
            versions.Add("-b", "maxwidth=1000&maxheight=1000&format=jpg"); //Fit inside 1900x1200 area

            int number = 1;
            //Loop through each uploaded file
            foreach (string fileKey in context.Request.Files.Keys)
            {
                HttpPostedFileBase file = context.Request.Files[fileKey];
                if (file.ContentLength <= 0) continue; //Skip unused file controls.

                //Get the physical path for the uploads folder and make sure it exists
                string uploadFolder = context.Server.MapPath("~/Images/Product/" + productId);
                if (!Directory.Exists(uploadFolder))
                    Directory.CreateDirectory(uploadFolder);

                string imageName = "0" + number.ToString();
                //Generate each version
                foreach (string suffix in versions.Keys)
                {
                    //Generate a filename (GUIDs are best).
                    string fileName = Path.Combine(uploadFolder, imageName + suffix);

                    //Let the image builder add the correct extension based on the output file type
                    fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                }
                number++;
            }
        }

        //add new saleoff
        //GET: Admin/AdminHome/addSaleOff
        public ActionResult addNewSaleOff()
        {
            return View();
        }

        //retrieve list saleoff
        //GET: Admin/AdminHome/retrieveAllSaleOff
        public ActionResult retrieveAllSaleOff()
        {
            return View();
        }

        //update saleoff
        //POST: Admin/AdminHome/updateSaleOff
        public ActionResult updateSaleOff()
        {
            return View();
        }
    }
}
